/*--------------------------------------------------------------------------
 *  Copyright 2011 Taro L. Saito
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *--------------------------------------------------------------------------*/
//--------------------------------------
// XerialJ
//
// Client.java
// Since: 2011/02/04 10:15:20
//
// $URL$
// $Author$
//--------------------------------------
package org.xerial.silk.weaver.cui;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelState;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.serialization.ObjectDecoder;
import org.jboss.netty.handler.codec.serialization.ObjectEncoder;
import org.xerial.util.log.Logger;
import org.xerial.util.opt.Argument;
import org.xerial.util.opt.Option;

public class Client extends WeaverCommand
{
    private static Logger _logger = Logger.getLogger(Client.class);

    @Option(symbol = "p", description = "port number. default:8080")
    int                   port    = 8080;

    @Option(symbol = "s", description = "hostname. default:localhost")
    String                host    = "localhost";

    @Argument(index = 0)
    String                message = "Hello World!";

    @Option(symbol = "n", description = "how many times send a message default n=1")
    int                   n       = 1;

    @Override
    public String name() {
        return "client";
    }

    @Override
    public String getOneLineDescription() {
        return "launch a client process";
    }

    @Override
    public Object getOptionHolder() {
        return this;
    }

    @Override
    public void execute(String[] args) throws Exception {

        ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
                Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(new ObjectEncoder(), new ObjectDecoder(), new ObjectClientHandler());
            }
        });

        ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
        for (int i = 0; i < n; ++i) {
            future.getChannel().getCloseFuture().awaitUninterruptibly();
        }
        bootstrap.releaseExternalResources();
        _logger.info("closed");
    }

    public class ObjectClientHandler extends SimpleChannelUpstreamHandler
    {
        private final AtomicLong transferredMessages = new AtomicLong();

        @Override
        public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
            if (e instanceof ChannelStateEvent && ((ChannelStateEvent) e).getState() != ChannelState.INTEREST_OPS) {
                _logger.info(e.toString());
            }
            super.handleUpstream(ctx, e);
        }

        @Override
        public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
            _logger.info("send a message: " + message);
            e.getChannel().write(message);
        }

        @Override
        public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
            transferredMessages.incrementAndGet();
            _logger.info("recieved a message from server: " + e.getMessage());
            e.getChannel().close();
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
            _logger.warn(e.getCause());
            e.getChannel().close();
        }
    }
}
